/*
 * Copyright (C) 2016 yixun All Rights Reserved.
 * 
 * NoticeServiceImpl.java
 */
package com.emm.yixun.basic.service.impl;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.emm.yixun.common.page.Page;
import com.emm.yixun.common.app.base.CommonResDTO;
import com.emm.yixun.common.model.MessageReceiver;
import com.emm.yixun.common.model.Notice;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.MessageReceiverDto;
import com.emm.yixun.common.model.dto.NoticeDto;
import com.emm.yixun.common.model.dto.ReceiverNoticeDto;
import com.emm.yixun.common.model.enums.DelFlagEnum;
import com.emm.yixun.common.model.enums.IsReadEnum;
import com.emm.yixun.common.model.enums.IsSendEnum;
import com.emm.yixun.common.model.enums.IsValidEnum;
import com.emm.yixun.common.model.enums.NoticeTypeEnum;
import com.emm.yixun.common.model.enums.ReceiveStatusEnum;
import com.emm.yixun.basic.service.AppPushService;
import com.emm.yixun.basic.service.MessageReceiverService;
import com.emm.yixun.basic.service.NoticeService;
import com.emm.yixun.basic.mapper.MessageReceiverMapper;
import com.emm.yixun.basic.mapper.NoticeMapper;


/**
 * [文件名称]<br>
 * NoticeServiceImpl.java<br>
 * <br>
 * [文件描述]<br>
 * InnoDB free: 10240 kB service interface impl<br>
 * <br>
 * [修改记录]<br>
 * 2016-05-16 18:03:24 创建 陶俊代码生成器<br>
 * 
 * @author 陶俊代码生成器
 * @version 1.00
 */
@Service("noticeService")
public class NoticeServiceImpl implements NoticeService {
	
	@Autowired
	private NoticeMapper mapper;
	
	@Autowired
	private MessageReceiverMapper messageReceiverMapper;
	
	@Autowired
	private MessageReceiverService messageReceiverService;
	@Autowired
	private AppPushService appPushService;
	
	/**
	 * @param entity 搜索条件
	 * @param begin 分页开始行数[不包含]
	 * @param end 分页结束行数[包含]
	 * @return 分页记录
	 */
	@Transactional(readOnly = true)
	public Page<Notice> getPageModel(NoticeDto entity,int begin,int end){
		Integer total = mapper.count(entity);
		List<Notice> rows = mapper.list(entity,begin,end);
	    Page<Notice> msr = new Page<Notice>(total, rows);
		return msr;
	}

	/**
	 * 查询列表
	 * @param entity 搜索条件
	 * @return 分页记录
	 */
	public List<Notice> selectListByDto(NoticeDto entity){
		return mapper.selectListByDto(entity);
	}
	
	/**
	 * 查询单个
	 * @param entity 搜索条件
	 * @return 分页记录
	 */
	public Notice selectByDto(NoticeDto entity){
		return mapper.selectByDto(entity);
	}
	
	/**
	 * @param entity 搜索条件
	 * @return 分页记录
	 */
	public Notice selectById(Long id){
		if(id!=null){
			return mapper.selectById(id);
		}
		return null;
	}
	/**
	 * @param entity 新增记录的详细信息
	 * @return 新增行数
	 */
	public NoticeDto create(NoticeDto entity) {
		entity.setCreateTime(Calendar.getInstance().getTime());
		mapper.add(entity);
		return entity;
	}

	/**
	 * @param entity 更新记录的详细信息
	 * @return 更新行数
	 */
	public int update(NoticeDto entity) {
		entity.setUpdateTime(Calendar.getInstance().getTime());
		return mapper.edit(entity);
	}
    
	/**
	 * @param entity 待删除的记录信息
	 * @return 删除行数
	 */
	public int destroy(NoticeDto entity) {
		return mapper.del(entity);
	}
	
	/**
	 * @param entity 新增或更新
	 * @return 新增行数
	 */
	public int saveOrUpdate(NoticeDto entity) {
		if(entity!=null&&entity.getId()!=null){
			return update(entity);
		}else{
			create(entity);
			return 1;
		}
	}

	public int updates(NoticeDto entity, String ids) {
		entity.setUpdateTime(Calendar.getInstance().getTime());
		return mapper.edits(entity, ids);
	}

	public NoticeDto createNotice(Map<String, String> noticeParamMap, List<User> userList, Long userId) {
		NoticeDto noticeDto = new NoticeDto();
		try{
			//生成消息,生成接收人信息
			//通知字典表中类型ID
			noticeDto.setDictionaryId(Long.parseLong(noticeParamMap.get("noticeDicId")));
			noticeDto.setNoticeType(NoticeTypeEnum.REMIND.getNo());
			noticeDto.setNoticeTempType(noticeParamMap.get("noticeTempType")); 
			noticeDto.setTitle(noticeParamMap.get("title"));
			noticeDto.setContent(noticeParamMap.get("sendMsg"));
			noticeDto.setIssueTime(Calendar.getInstance().getTime());
			if(noticeParamMap.get("timerNotice") != null){
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				noticeDto.setTimerNotice(sdf.parse(noticeParamMap.get("timerNotice")));
			}
			noticeDto.setMerchantId(Long.parseLong(noticeParamMap.get("merchantId")));
			noticeDto.setUserCode(noticeParamMap.get("userCode"));
			noticeDto.setAccessCode(noticeParamMap.get("accessCode"));
			if(noticeParamMap.get("projectCode") != null){
				noticeDto.setProjectCode(noticeParamMap.get("projectCode"));
			}
			noticeDto.setIsValid(IsValidEnum.VALID.getNo());
			noticeDto.setIsRead(IsReadEnum.UNREAD.getNo());
			noticeDto.setIsSend(IsSendEnum.UNSEND.getNo());
			noticeDto.setCreateUserId(Long.parseLong(noticeParamMap.get("createUserId")));
			noticeDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		    /*
             * (ym) 提醒内容增加超链接 start
             * */
            noticeDto.setRemark(noticeParamMap.get("replaceValues"));
            /*
             * (ym) 提醒内容增加超链接 end
             * */
			noticeDto = create(noticeDto);
			//添加接收人
			if(userList != null){
				for(User user: userList){
					//userId不为空,代表此用户不参与消息
					if(null != userId && user.getId() == userId){
						continue;
					}
					MessageReceiverDto msgRecDto = new MessageReceiverDto();
					msgRecDto.setNoticeId(noticeDto.getId());
					msgRecDto.setReceiverId(user.getId());
					msgRecDto.setReceiveStatus(ReceiveStatusEnum.UNRECEIVED.getNo());
					msgRecDto.setMerchantId(Long.parseLong(noticeParamMap.get("merchantId")));
					msgRecDto.setCreateUserId(Long.parseLong(noticeParamMap.get("createUserId")));
					msgRecDto.setUpdateTime(new Date());
					msgRecDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
					messageReceiverService.create(msgRecDto);
				}
			}
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
		return noticeDto;
	}

	public CommonResDTO pushMsg(String projectCode, String projectName, NoticeDto noticeDto, String actionTitle) {
		CommonResDTO resDto = new CommonResDTO();
		try {
	 		MessageReceiverDto mrDto = new MessageReceiverDto();
	 		mrDto.setNoticeId(noticeDto.getId());
	 		mrDto.setIsSend(IsSendEnum.UNSEND.getNo());
	   	 	List<MessageReceiverDto> mrList = messageReceiverService.selectPushMsgListByDto(mrDto);
	   	 	
	   	 	if(mrList != null && mrList.size() > 0){
	   	 /*		String noticeIds = "";
	   	 		String msgRecIds = "";
	   	 		Set<String> noticeIdSet = new HashSet<String>();*/
	   	 		for(MessageReceiverDto msgRecDto: mrList){
	   	 			//开始推送消息
		   	 		Map<String, String> pushMap = new HashMap<String, String>();
			   	 	pushMap.put("action", actionTitle);
			   	 	pushMap.put("remindCategoryId", String.valueOf(msgRecDto.getDictionaryId()));
//			   	 	pushMap.put("pushType", msgRecDto.getNoticeTempType());
			   	 	pushMap.put("pushType", "SHSQ");
			   	    pushMap.put("projectCode",projectCode);
			   	    pushMap.put("projectName", projectName);
					String context = msgRecDto.getContent();
					appPushService.pushMessage(String.valueOf(msgRecDto.getReceiverId()), context, msgRecDto.getTitle(), pushMap);
					
/*					//消息ID,Set
					noticeIdSet.add(String.valueOf(msgRecDto.getNoticeId()));
					//消息接收人ID'S
					if(StringUtils.isNotEmpty(msgRecIds)){
						msgRecIds += ",";
					}
					msgRecIds += String.valueOf(msgRecDto.getId());*/
	   	 		}
	   	 		
	   	 		//需更新消息ID'S
/*	   	 		if(!noticeIdSet.isEmpty()){
					for(String noticeId: noticeIdSet){
						if(StringUtils.isNotEmpty(noticeIds)){
							noticeIds += ",";
						}
						noticeIds += noticeId;
		   	 		}
	   	 		}*/
	   	 		//更新消息
	   	 	   NoticeDto updateNoticeDto = new NoticeDto();
	   	 	   updateNoticeDto.setId(noticeDto.getId());
	   	 	   updateNoticeDto.setIsSend(IsSendEnum.SEND.getNo());
	   	 	   update(updateNoticeDto);
	   	 		//updates(noticeDto, noticeIds);
	   	 		//更新接收人
	   	 		/*MessageReceiverDto updateMRDto = new MessageReceiverDto();
	   	 		updateMRDto.setIsSend(IsSendEnum.SEND.getNo());
	   	 		messageReceiverService.updates(updateMRDto, msgRecIds);*/
			
	   	 		resDto.setResult("1");
	   	 		return resDto;
	   	 	}
		} catch (Exception e) {
			e.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("消息发送失败: " + e);
			resDto.setResult("0");
			return resDto;
		}
		return resDto;
	}

	/**
	 * 统计数量
	 */
	public int count(NoticeDto entity) {
		return mapper.count(entity);
	}

	public Page<Notice> getNoticeList(NoticeDto entity, int begin, int end) {
		Integer total = mapper.noticeCount(entity);
		List<Notice> rows = mapper.noticeList(entity,begin,end);
	    Page<Notice> msr = new Page<Notice>(total, rows);
		return msr;
	}
	
	/**
	 * 统计数量(根据字典ID,统计该字典对应的消息类型拥有的数量)
	 */
	public int noticeCount(NoticeDto entity) {
		return mapper.noticeCount(entity);
	}
	
	/**
	 * 查询用户消息并分页
	 */
	public Page<ReceiverNoticeDto>  receiverNoticePage(ReceiverNoticeDto receiverNoticeDto,int begin,int pageSize){
		Integer total =mapper.receiverNoticeListCount(receiverNoticeDto);
		List<ReceiverNoticeDto> rows=mapper.receiverNoticeList(receiverNoticeDto,begin,pageSize);
		Page<ReceiverNoticeDto> msr = new Page<ReceiverNoticeDto>(total, rows);
		msr.setPageSize(pageSize);
		//更新消息状态为已读
		for(ReceiverNoticeDto rnd : rows){
			try {
				if(StringUtils.isNotBlank(rnd.getRemark())){
					//rnd.setContent(MsgUtil.addLink(rnd.getContent(), rnd.getRemark()));
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			Long id=rnd.getReceiverId();
			MessageReceiver messageReceiver=new MessageReceiver();
			messageReceiver.setId(id);
			messageReceiver.setReceiveStatus(ReceiveStatusEnum.RECEIVED.getNo());
			messageReceiverMapper.edit(messageReceiver);
		}
		return msr;
	}
	
	/**
	 * 查询用户消息条数
	 */
	public int  receiverNoticeCount(ReceiverNoticeDto receiverNoticeDto){
		return mapper.receiverNoticeListCount(receiverNoticeDto);
	}
	
}
